package com.mlatent.mvvmproject.ui.login

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.util.ToastUtil
import com.mlatent.mvvmproject.R
import com.mlatent.mvvmproject.app.base.BaseFragment
import com.mlatent.mvvmproject.app.ext.hideSoftKeyboard
import com.mlatent.mvvmproject.app.util.CacheUtils
import kotlinx.android.synthetic.main.fragment_login.*

class LoginFragment : BaseFragment<LoginRegisterViewModel>() {

    override fun layoutId() = R.layout.fragment_login

    override fun initView(savedInstanceState: Bundle?) {
        ivClose.setOnClickListener {
            hideSoftKeyboard(activity)
            activity?.finish()
        }
        btnLogin.setOnClickListener {
            mViewModel.username = editUserName.text.toString()
            mViewModel.password = editPassword.text.toString()
            when {
                TextUtils.isEmpty(mViewModel.username) -> {
                    ToastUtil.showShort(context, "请输入用户名")
                }
                TextUtils.isEmpty(mViewModel.password) -> {
                    ToastUtil.showShort(context, "请输入密码")
                }
                else -> {
                    mViewModel.login()
                }
            }
        }
    }

    override fun lazyLoadData() {
        editUserName.setText(mViewModel.username)
    }

    override fun createObserver() {
        mViewModel.userInfo.observe(this, Observer { resultState ->
            parseState(resultState, {
                CacheUtils.setUserInfo(it)
                cacheViewModel.userInfo.postValue(CacheUtils.getUserInfo())
                cacheViewModel.isLogin.postValue(CacheUtils.isLogin())
                ToastUtil.showShort(context, "登陆成功")
                hideSoftKeyboard(activity)
                activity?.finish()
            }, {
                ToastUtil.showShort(context, it.message)
            })

        })
    }
}